package com.starbugs.wehcat.data;

import com.starbugs.wehcat.pojo.Ingredient;
import com.starbugs.wehcat.pojo.Taco;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.Arrays;
import java.util.Date;

/**
 * @author huahuadavids
 */
@Repository
public class JdbcTacoRepository implements TacoRepository {

  private static int id = 0;

  private JdbcTemplate jdbc;

  public JdbcTacoRepository(JdbcTemplate jdbc) {
    this.jdbc = jdbc;
  }

  @Override
  public Taco save(Taco taco) {
    long tacoId = saveTacoInfo(taco);
    taco.setId(tacoId);
    for (Ingredient ingredient : taco.getIngredients()) {
      saveIngredientToTaco(ingredient, tacoId);
    }

    return taco;
  }

  // todo 应该会返回插入数据的id，但是没返回 h2数据库的问题？？

  private long saveTacoInfo1(Taco taco){
    taco.setCreateAt(new Date());

    PreparedStatementCreator psc =
        new PreparedStatementCreatorFactory(
            "insert into Taco (name, createdAt) values (?, ?)",
            Types.VARCHAR, Types.TIMESTAMP
        ).newPreparedStatementCreator(
            Arrays.asList(
                taco.getName(),
                new Timestamp(taco.getCreateAt().getTime())
            )
        );
    // KeyHolder将会为我们提供生成的taco ID
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(psc, keyHolder);

    if(keyHolder.getKey() != null){
      return keyHolder.getKey().longValue();
    }
    return 1111;
  }

  private long saveTacoInfo(Taco taco){
    taco.setCreateAt(new Date());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(new PreparedStatementCreator() {
      @Override
      public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
        PreparedStatement updateSales =  conn.prepareStatement("insert into Taco (name, createdAt) values(?,?)");
        updateSales.setTimestamp(2, new Timestamp(taco.getCreateAt().getTime()));
        updateSales.setString(1, taco.getName());
        return updateSales;
      }
    },keyHolder);
    JdbcTacoRepository.id++;
    // fixme 手动查询最后一次插入的结果的id返回
    return JdbcTacoRepository.id;
  }


  private void saveIngredientToTaco(Ingredient ingredient, long tacoId){
     try {
       jdbc.update("insert into Taco_Ingredients (taco, ingredient)" + "values (? , ?)", tacoId, ingredient.getId());
     } catch (Exception e){
       System.out.println(e);
     }finally {
       System.out.println("finish");
     }

  }



}
